<template>
  <div class="p-6">
    <div class="flex justify-between items-center mb-6">
      <div>
        <h1 class="text-3xl font-bold text-gray-900 dark:text-white">工具管理</h1>
        <p class="text-gray-600 dark:text-gray-400 mt-2">管理开发工具和资源</p>
      </div>
      <button
        @click="openCreateDialog"
        class="btn btn-primary flex items-center gap-2"
      >
        <Icon name="heroicons:plus" class="w-5 h-5" />
        添加工具
      </button>
    </div>

      <!-- 工具列表 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div
          v-for="tool in tools"
          :key="tool.id"
          class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 hover:shadow-lg transition-shadow"
        >
          <div class="flex items-start gap-4">
            <div class="w-16 h-16 rounded-lg bg-gray-100 dark:bg-gray-700 flex items-center justify-center overflow-hidden flex-shrink-0">
              <img
                v-if="tool.logo"
                :src="getImageUrl(tool.logo)"
                :alt="tool.name"
                class="w-full h-full object-cover"
              />
              <span v-else class="text-2xl">🔧</span>
            </div>
            <div class="flex-1 min-w-0">
              <h3 class="text-lg font-semibold text-gray-900 dark:text-white truncate">{{ tool.name }}</h3>
              <p class="text-sm text-gray-500 dark:text-gray-400 mt-1 line-clamp-2">
                {{ tool.description }}
              </p>
              <div class="flex items-center gap-4 mt-3 text-sm text-gray-500 dark:text-gray-400">
                <span>👁️ {{ tool.views }}</span>
                <span>👍 {{ tool.upvotes }}</span>
                <span>⭐ {{ Number(tool.rating).toFixed(1) }}</span>
              </div>
              <div class="flex gap-2 mt-4">
                <button
                  @click="openEditDialog(tool)"
                  class="text-sm text-blue-600 hover:text-blue-700 font-medium"
                >
                  编辑
                </button>
                <button
                  @click="deleteTool(tool)"
                  class="text-sm text-red-600 hover:text-red-700 font-medium"
                >
                  删除
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <Pagination
        v-if="totalPages > 1"
        :current-page="currentPage"
        :total-pages="totalPages"
        :total="total"
        :page-size="pageSize"
        @update:current-page="handlePageChange"
        class="mt-8"
      />

      <!-- 创建/编辑对话框 - 优化版 -->
      <div v-if="showDialog" class="fixed inset-0 bg-black/50 z-50 flex items-start justify-center overflow-y-auto">
        <div class="bg-white dark:bg-gray-800 rounded-lg w-full max-w-6xl mx-4 my-8 shadow-2xl">
          <!-- 头部 - 固定 -->
          <div class="sticky top-0 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-6 py-4 rounded-t-lg z-10">
            <div class="flex items-center justify-between">
              <h2 class="text-2xl font-bold text-gray-900 dark:text-white">
            {{ isEditing ? '编辑工具' : '添加工具' }}
          </h2>
              <button
                type="button"
                @click="closeDialog"
                class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transition-colors"
              >
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>

            <!-- 标签页切换 -->
            <div class="flex gap-4 mt-4 border-b border-gray-200 dark:border-gray-700 -mb-px">
              <button
                type="button"
                @click="activeFormTab = 'basic'"
                :class="[
                  'px-4 py-2 font-medium text-sm border-b-2 transition-colors',
                  activeFormTab === 'basic'
                    ? 'border-blue-600 text-blue-600 dark:text-blue-400'
                    : 'border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400'
                ]"
              >
                📋 基础信息
              </button>
              <button
                type="button"
                @click="activeFormTab = 'details'"
                :class="[
                  'px-4 py-2 font-medium text-sm border-b-2 transition-colors',
                  activeFormTab === 'details'
                    ? 'border-blue-600 text-blue-600 dark:text-blue-400'
                    : 'border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400'
                ]"
              >
                📝 详细信息
              </button>
            </div>
          </div>
          
          <form @submit.prevent="saveTool">
            <!-- 表单内容区域 - 可滚动 -->
            <div class="px-6 py-6 max-h-[calc(100vh-240px)] overflow-y-auto">
              
              <!-- 基础信息标签页 -->
              <div v-show="activeFormTab === 'basic'" class="space-y-6">
            <!-- 基本信息 -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  工具名称 *
                </label>
                <input
                  v-model="formData.name"
                  type="text"
                  required
                  class="input"
                  placeholder="例如：Visual Studio Code"
                />
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  URL地址 *
                </label>
                <input
                  v-model="formData.url"
                  type="url"
                  required
                  class="input"
                  placeholder="https://example.com"
                />
              </div>
            </div>

            <!-- Logo上传 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Logo图片
              </label>
              <div class="flex items-center gap-4">
                <div v-if="formData.logo" class="relative w-20 h-20 rounded-lg overflow-hidden bg-gray-100 dark:bg-gray-700">
                  <img :src="getImageUrl(formData.logo)" alt="Logo" class="w-full h-full object-cover" />
                  <button
                    type="button"
                    @click="formData.logo = ''"
                    class="absolute top-1 right-1 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center hover:bg-red-600"
                  >
                    ×
                  </button>
                </div>
                <div class="flex-1">
                  <input
                    ref="logoInput"
                    type="file"
                    accept="image/*"
                    @change="uploadLogo"
                    class="hidden"
                  />
                  <button
                    type="button"
                    @click="logoInput?.click()"
                    class="btn btn-outline"
                    :disabled="uploading"
                  >
                    {{ uploading ? '上传中...' : '选择Logo' }}
                  </button>
                  <p class="text-xs text-gray-500 mt-1">支持 JPG、PNG、GIF、WebP，最大5MB</p>
                </div>
              </div>
            </div>

            <!-- 截图上传 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                产品截图
              </label>
              <div class="flex items-center gap-4">
                <div v-if="formData.screenshot" class="relative w-32 h-20 rounded-lg overflow-hidden bg-gray-100 dark:bg-gray-700">
                  <img :src="getImageUrl(formData.screenshot)" alt="Screenshot" class="w-full h-full object-cover" />
                  <button
                    type="button"
                    @click="formData.screenshot = ''"
                    class="absolute top-1 right-1 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center hover:bg-red-600"
                  >
                    ×
                  </button>
                </div>
                <div class="flex-1">
                  <input
                    ref="screenshotInput"
                    type="file"
                    accept="image/*"
                    @change="uploadScreenshot"
                    class="hidden"
                  />
                  <button
                    type="button"
                    @click="screenshotInput?.click()"
                    class="btn btn-outline"
                    :disabled="uploading"
                  >
                    {{ uploading ? '上传中...' : '选择截图' }}
                  </button>
                  <p class="text-xs text-gray-500 mt-1">建议16:9比例，最大5MB</p>
                </div>
              </div>
            </div>

            <!-- 描述 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                工具描述 *
              </label>
              <textarea
                v-model="formData.description"
                required
                rows="3"
                class="input"
                placeholder="简要描述工具的功能和特点"
              ></textarea>
            </div>

            <!-- 分类和标签 -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  分类 *
                </label>
                <select v-model="formData.categoryId" required class="input">
                  <option value="">请选择分类</option>
                  <option v-for="cat in categories" :key="cat.id" :value="cat.id">
                    {{ cat.name }}
                  </option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  定价模式
                </label>
                <input
                  v-model="formData.pricing"
                  type="text"
                  class="input"
                  placeholder="例如：免费 / $9/月"
                />
              </div>
            </div>

            <!-- 标记 -->
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
              <label class="flex items-center gap-2">
                <input v-model="formData.isFree" type="checkbox" class="rounded" />
                <span class="text-sm text-gray-700 dark:text-gray-300">免费</span>
              </label>
              <label class="flex items-center gap-2">
                <input v-model="formData.isPremium" type="checkbox" class="rounded" />
                <span class="text-sm text-gray-700 dark:text-gray-300">会员专属</span>
              </label>
              <label class="flex items-center gap-2">
                <input v-model="formData.isFeatured" type="checkbox" class="rounded" />
                <span class="text-sm text-gray-700 dark:text-gray-300">推荐</span>
              </label>
              <label class="flex items-center gap-2">
                <input v-model="formData.isSponsored" type="checkbox" class="rounded" />
                <span class="text-sm text-gray-700 dark:text-gray-300">赞助</span>
              </label>
            </div>
              </div>

              <!-- 详细信息标签页 -->
              <div v-show="activeFormTab === 'details'" class="space-y-6">
                
                <!-- 多张截图 - 支持上传和URL -->
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                  📸 工具截图（多张）
                </label>
                
                <!-- 已上传的截图预览 -->
                <div v-if="formData.screenshots.length > 0" class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
                  <div v-for="(screenshot, index) in formData.screenshots" :key="`preview-${index}`" class="relative group">
                    <div class="relative w-full h-32 rounded-lg overflow-hidden bg-gray-100 dark:bg-gray-700">
                      <img v-if="screenshot" :src="getImageUrl(screenshot)" :alt="`截图 ${index + 1}`" class="w-full h-full object-cover" />
                      <div v-else class="w-full h-full flex items-center justify-center text-gray-400">
                        <span class="text-sm">未设置</span>
                      </div>
                      <div class="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                        <button
                          type="button"
                          @click="removeScreenshot(index)"
                          class="bg-red-500 text-white rounded-full w-8 h-8 flex items-center justify-center hover:bg-red-600 transition-colors"
                        >
                          ×
                        </button>
                      </div>
                    </div>
                    <p class="text-xs text-gray-500 dark:text-gray-400 mt-1 truncate">截图 {{ index + 1 }}</p>
                  </div>
                </div>

                <!-- 上传按钮 -->
                <div class="flex gap-3 mb-3">
                  <input
                    ref="multipleScreenshotsInput"
                    type="file"
                    accept="image/*"
                    multiple
                    @change="uploadMultipleScreenshots"
                    class="hidden"
                  />
                  <button
                    type="button"
                    @click="multipleScreenshotsInput?.click()"
                    class="btn btn-outline"
                    :disabled="uploading"
                  >
                    📤 {{ uploading ? '上传中...' : '上传多张截图' }}
                  </button>
                  <button
                    type="button"
                    @click="formData.screenshots.push('')"
                    class="btn btn-secondary"
                  >
                    🔗 添加URL链接
                  </button>
                </div>
                <p class="text-xs text-gray-500 mb-4">支持同时选择多张图片上传，或手动添加在线图片URL</p>

                <!-- URL输入列表 -->
                <div class="space-y-2">
                  <div v-for="(screenshot, index) in formData.screenshots" :key="`url-${index}`" class="flex gap-2">
                    <input
                      v-model="formData.screenshots[index]"
                      type="url"
                      class="input flex-1 text-sm"
                      placeholder="https://example.com/screenshot.png"
                    />
                    <button
                      type="button"
                      @click="removeScreenshot(index)"
                      class="btn btn-outline text-red-600 px-3"
                    >
                      删除
                    </button>
                  </div>
                </div>
              </div>

              <!-- 使用场景 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  使用场景
                </label>
                <textarea
                  v-model="formData.useCases"
                  rows="4"
                  class="input"
                  placeholder="描述该工具适用的场景，例如：前端开发、数据分析、团队协作等"
                ></textarea>
              </div>

              <!-- 核心特性 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  核心特性
                </label>
                <div class="space-y-2">
                  <div v-for="(feature, index) in formData.features" :key="index" class="flex gap-2">
                    <input
                      v-model="formData.features[index]"
                      type="text"
                      class="input flex-1"
                      placeholder="特性描述"
                    />
                    <button
                      type="button"
                      @click="formData.features.splice(index, 1)"
                      class="btn btn-outline text-red-600"
                    >
                      删除
                    </button>
                  </div>
                  <button
                    type="button"
                    @click="formData.features.push('')"
                    class="btn btn-outline text-sm"
                  >
                    + 添加特性
                  </button>
                </div>
              </div>

              <!-- 优点 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  优点
                </label>
                <div class="space-y-2">
                  <div v-for="(pro, index) in formData.pros" :key="index" class="flex gap-2">
                    <input
                      v-model="formData.pros[index]"
                      type="text"
                      class="input flex-1"
                      placeholder="优点描述"
                    />
                    <button
                      type="button"
                      @click="formData.pros.splice(index, 1)"
                      class="btn btn-outline text-red-600"
                    >
                      删除
                    </button>
                  </div>
                  <button
                    type="button"
                    @click="formData.pros.push('')"
                    class="btn btn-outline text-sm"
                  >
                    + 添加优点
                  </button>
                </div>
              </div>

              <!-- 缺点 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  缺点
                </label>
                <div class="space-y-2">
                  <div v-for="(con, index) in formData.cons" :key="index" class="flex gap-2">
                    <input
                      v-model="formData.cons[index]"
                      type="text"
                      class="input flex-1"
                      placeholder="缺点描述"
                    />
                    <button
                      type="button"
                      @click="formData.cons.splice(index, 1)"
                      class="btn btn-outline text-red-600"
                    >
                      删除
                    </button>
                  </div>
                  <button
                    type="button"
                    @click="formData.cons.push('')"
                    class="btn btn-outline text-sm"
                  >
                    + 添加缺点
                  </button>
                </div>
              </div>

              <!-- 推荐理由 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  推荐理由
                </label>
                <textarea
                  v-model="formData.recommendation"
                  rows="3"
                  class="input"
                  placeholder="为什么推荐这个工具？它的核心价值是什么？"
                ></textarea>
              </div>

              <!-- 相关链接 -->
              <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    官方文档
                  </label>
                  <input
                    v-model="formData.docsUrl"
                    type="url"
                    class="input"
                    placeholder="https://docs.example.com"
                  />
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    GitHub仓库
                  </label>
                  <input
                    v-model="formData.githubUrl"
                    type="url"
                    class="input"
                    placeholder="https://github.com/user/repo"
                  />
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    视频介绍
                  </label>
                  <input
                    v-model="formData.videoUrl"
                    type="url"
                    class="input"
                    placeholder="https://youtube.com/watch?v=xxx"
                  />
                </div>
              </div>

              <!-- 自定义相关链接 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  其他相关链接
                </label>
                <div class="space-y-2">
                  <div v-for="(link, index) in formData.relatedLinks" :key="index" class="flex gap-2">
                    <input
                      v-model="link.title"
                      type="text"
                      class="input w-1/3"
                      placeholder="链接标题"
                    />
                    <input
                      v-model="link.url"
                      type="url"
                      class="input flex-1"
                      placeholder="https://example.com"
                    />
                    <button
                      type="button"
                      @click="formData.relatedLinks.splice(index, 1)"
                      class="btn btn-outline text-red-600"
                    >
                      删除
                    </button>
                  </div>
              <button
                    type="button"
                    @click="formData.relatedLinks.push({ title: '', url: '' })"
                    class="btn btn-outline text-sm"
                  >
                    + 添加相关链接
              </button>
                </div>
              </div>
              </div>
            </div>

            <!-- 底部按钮 - 固定 -->
            <div class="sticky bottom-0 bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 px-6 py-4 rounded-b-lg flex gap-4 justify-end">
              <button
                type="button"
                @click="closeDialog"
                class="btn btn-outline px-6"
              >
                取消
              </button>
              <button
                type="submit"
                class="btn btn-primary px-8"
                :disabled="saving || uploading"
              >
                <span v-if="saving">保存中...</span>
                <span v-else>{{ isEditing ? '保存更改' : '创建工具' }}</span>
              </button>
            </div>
          </form>
        </div>
      </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

definePageMeta({
  layout: 'admin',
  middleware: ['auth'],
})

const $api = useNuxtApp().$api
const { getTools } = useTools()
const toast = useToast()

const tools = ref<any[]>([])
const categories = ref<any[]>([])
const showDialog = ref(false)
const isEditing = ref(false)
const uploading = ref(false)
const saving = ref(false)
const activeFormTab = ref('basic') // 表单标签页状态

// 分页相关
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const totalPages = ref(0)

const formData = ref({
  id: null,
  name: '',
  slug: '',
  url: '',
  logo: '',
  screenshot: '',
  description: '',
  categoryId: '',
  pricing: '',
  isFree: true,
  isPremium: false,
  isFeatured: false,
  isSponsored: false,
  // 新增详细字段
  screenshots: [] as string[],
  useCases: '',
  features: [] as string[],
  pros: [] as string[],
  cons: [] as string[],
  recommendation: '',
  docsUrl: '',
  githubUrl: '',
  videoUrl: '',
  relatedLinks: [] as { title: string; url: string }[],
})

const logoInput = ref<HTMLInputElement | null>(null)
const screenshotInput = ref<HTMLInputElement | null>(null)
const multipleScreenshotsInput = ref<HTMLInputElement | null>(null)

// 获取工具列表
const loadTools = async () => {
  try {
    const result = await getTools({ 
      page: currentPage.value,
      limit: pageSize.value 
    }) as any
    tools.value = result.data
    total.value = result.total
    totalPages.value = result.totalPages
  } catch (error) {
    toast.error('加载工具列表失败')
  }
}

// 分页相关方法
const goToPage = (page: number) => {
  currentPage.value = page
  loadTools()
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    loadTools()
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    loadTools()
  }
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  loadTools()
}

// 获取分类列表
const loadCategories = async () => {
  try {
    const result = await $api('/categories') as any
    categories.value = result
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

// 打开创建对话框
const openCreateDialog = () => {
  isEditing.value = false
  formData.value = {
    id: null,
    name: '',
    slug: '',
    url: '',
    logo: '',
    screenshot: '',
    description: '',
    categoryId: '',
    pricing: '',
    isFree: true,
    isPremium: false,
    isFeatured: false,
    isSponsored: false,
    // 新增详细字段
    screenshots: [],
    useCases: '',
    features: [],
    pros: [],
    cons: [],
    recommendation: '',
    docsUrl: '',
    githubUrl: '',
    videoUrl: '',
    relatedLinks: [],
  }
  showDialog.value = true
}

// 打开编辑对话框
const openEditDialog = (tool: any) => {
  isEditing.value = true
  formData.value = {
    id: tool.id,
    name: tool.name,
    slug: tool.slug,
    url: tool.url,
    logo: tool.logo || '',
    screenshot: tool.screenshot || '',
    description: tool.description,
    categoryId: tool.categoryId,
    pricing: tool.pricing || '',
    isFree: tool.isFree,
    isPremium: tool.isPremium,
    isFeatured: tool.isFeatured,
    isSponsored: tool.isSponsored,
    // 新增详细字段
    screenshots: tool.screenshots || [],
    useCases: tool.useCases || '',
    features: tool.features || [],
    pros: tool.pros || [],
    cons: tool.cons || [],
    recommendation: tool.recommendation || '',
    docsUrl: tool.docsUrl || '',
    githubUrl: tool.githubUrl || '',
    videoUrl: tool.videoUrl || '',
    relatedLinks: tool.relatedLinks || [],
  }
  showDialog.value = true
}

// 关闭对话框
const closeDialog = () => {
  showDialog.value = false
}

// 上传Logo
const uploadLogo = async (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (!file) return

  try {
    uploading.value = true
    const formDataUpload = new FormData()
    formDataUpload.append('file', file)
    formDataUpload.append('type', 'tool')

    const result = await $api('/upload/single', {
      method: 'POST',
      body: formDataUpload,
    }) as any

    formData.value.logo = result.data.url
    toast.success('Logo上传成功')
  } catch (error) {
    console.error('上传失败:', error)
    toast.error('Logo上传失败')
  } finally {
    uploading.value = false
  }
}

// 上传截图
const uploadScreenshot = async (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (!file) return

  try {
    uploading.value = true
    const formDataUpload = new FormData()
    formDataUpload.append('file', file)
    formDataUpload.append('type', 'tool')

    const result = await $api('/upload/single', {
      method: 'POST',
      body: formDataUpload,
    }) as any

    formData.value.screenshot = result.data.url
    toast.success('截图上传成功')
  } catch (error) {
    console.error('上传失败:', error)
    toast.error('截图上传失败')
  } finally {
    uploading.value = false
  }
}

// 上传多张截图
const uploadMultipleScreenshots = async (event: Event) => {
  const files = (event.target as HTMLInputElement).files
  if (!files || files.length === 0) return

  try {
    uploading.value = true
    const uploadPromises = Array.from(files).map(async (file) => {
      const formDataUpload = new FormData()
      formDataUpload.append('file', file)
      formDataUpload.append('type', 'tool')

      const result = await $api('/upload/single', {
        method: 'POST',
        body: formDataUpload,
      }) as any

      return result.data.url
    })

    const uploadedUrls = await Promise.all(uploadPromises)
    formData.value.screenshots.push(...uploadedUrls)
    toast.success(`成功上传 ${uploadedUrls.length} 张截图`)
    
    // 清空input以便可以再次上传相同文件
    ;(event.target as HTMLInputElement).value = ''
  } catch (error) {
    console.error('上传失败:', error)
    toast.error('截图上传失败')
  } finally {
    uploading.value = false
  }
}

// 删除指定截图
const removeScreenshot = (index: number) => {
  formData.value.screenshots.splice(index, 1)
}

// 生成slug
const generateSlug = (name: string) => {
  return name
    .toLowerCase()
    .replace(/\s+/g, '-')
    .replace(/[^\w\-]+/g, '')
    .replace(/\-\-+/g, '-')
    .replace(/^-+/, '')
    .replace(/-+$/, '')
}

// 保存工具
const saveTool = async () => {
  try {
    saving.value = true

    // 自动生成 slug
    if (!formData.value.slug) {
      formData.value.slug = generateSlug(formData.value.name)
    }

    // 准备提交的数据，去除 id 字段
    const { id, ...submitData } = formData.value

    if (isEditing.value) {
      // 更新
      await $api(`/tools/${id}`, {
        method: 'PATCH',
        body: submitData,
      })
      toast.success('工具更新成功')
    } else {
      // 创建
      await $api('/tools', {
        method: 'POST',
        body: submitData,
      })
      toast.success('工具创建成功')
    }

    closeDialog()
    loadTools()
  } catch (error: any) {
    console.error('保存失败:', error)
    toast.error(error.data?.message || '保存失败')
  } finally {
    saving.value = false
  }
}

// 删除工具
const deleteTool = async (tool: any) => {
  if (!confirm(`确定要删除"${tool.name}"吗？`)) return

  try {
    await $api(`/tools/${tool.id}`, {
      method: 'DELETE',
    })
    toast.success('删除成功')
    loadTools()
  } catch (error) {
    console.error('删除失败:', error)
    toast.error('删除失败')
  }
}

// 使用统一的图片URL工具
const { getImageUrl } = useImageUrl()

onMounted(() => {
  loadTools()
  loadCategories()
})
</script>
